package com.itheima.config;


import com.alibaba.fastjson.JSON;
import com.itheima.exception.SystemException;
import com.itheima.metaobjecthandler.BaseContext;
import com.itheima.pojo.Code;
import com.itheima.pojo.Employee;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Log4j2
@Component
public class JWTInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("token拦截器======");
        long id = Thread.currentThread().getId();
        log.info("线程id为：{}",id);
        // 获取请求头中令牌
            String token = request.getHeader("Authorization");
            //数据库验证token
            Object o = redisTemplate.opsForValue().get(token);
        //token过期，在redis中不存在
        if (o==null){
            throw new SystemException(Code.ERR401, null);
        }
        Employee employee = JSON.parseObject(o.toString(), Employee.class);
        if (employee != null){
            BaseContext.setCurrentId(employee.getId());
            log.info("用户已登录，用户id:{}",employee.getId());
        }
        log.info("当前访问的用户是："+employee.getName());

        return true;
        }
    }
